package cn.coufran.springboot.starter.auth.impl.token;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author Coufran
 * @version 1.0.0
 * @since 1.0.0
 */
public class FileKeyStore implements KeyStore {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileKeyStore.class);

    private static final String FILE_NAME_KEY = "default.key";

    private String fileName;

    public FileKeyStore() {
        this(FILE_NAME_KEY);
    }

    public FileKeyStore(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void save(byte[] key) {
        Path keyFile = Paths.get(this.fileName);
        File keyFileDir = keyFile.toFile().getAbsoluteFile().getParentFile();
        if (!keyFileDir.exists()) {
            boolean mkdirSuccess = keyFileDir.mkdirs();
            if (!mkdirSuccess) {
                LOGGER.error("save key error, mkdir fail: {}", keyFileDir.getParent());
            }
        }
        try {
            Files.write(keyFile, key);
        } catch (IOException e) {
            LOGGER.error("save key fail, {}", e.getMessage());
            LOGGER.info("save key fail", e);
        }
    }

    @Override
    public byte[] load() {
        Path keyFile = Paths.get(this.fileName);
        if (!Files.exists(keyFile)) {
            return null;
        }
        try {
            return Files.readAllBytes(keyFile);
        } catch (IOException e) {
            LOGGER.error("read key fail, {}", e.getMessage());
            LOGGER.info("read key fail", e);
            return null;
        }
    }
}
